#pragma once
#include <iostream>
#include "Protocol.hpp"

class Calculator 
{
public:
    Calculator(){}

    Response Execute(const Request& req)
    {
        Response resp;
        switch(req.Oper())
        {
        case '+':
            resp.SetResult(req.X() + req.Y());
            break;
        case '-':
            resp.SetResult(req.X() - req.Y());
            break;
        case '*':
            resp.SetResult(req.X() * req.Y());
            break;
        case '/':
            {
                if(req.Y() == 0)
                {
                    resp.SetCode(1); //1 就是除0
                }
                else
                {
                    resp.SetResult(req.X() / req.Y());
                }
            }
            break;
        case '%':
            {
                if(req.Y() == 0)
                {
                    resp.SetCode(2); //2 就是mod 0
                }
                else
                {
                    resp.SetResult(req.X() / req.Y());
                }
            }
            break;
        default:
            resp.SetCode(3); //0 3 用户发来的计算类型，无法识别 
            break;
        }
        return resp;
    }

    ~Calculator()
    {}
};

Calculator cal;

std::string HandleRequest(std::string &inbuffer)
{
    std::string request_str;
    std::string result_str;
    while(Decode(inbuffer, &request_str))
    {
        std::string resp_str;
        // 1. 反序列化
        if(request_str.empty()) 
            break;
        Request req;
        if(!req.Deserialize(request_str))
            break;

        // 2. 处理请求
        Response resp = cal.Execute(req);

        // 3. 序列化响应
        resp.Serialize(resp_str);

        // 4. 添加长度
        Encode(resp_str);

        // 添加所有应答
        result_str += resp_str;
    }

    return result_str;
}